#include <i386/stdlib.h>
#include <i386/string.h>
#include <i386/limits.h>
#include <i386/float.h>
#include <i386/mem.h>
#include <stdarg.h>
#include <ctype.h>
#include <math.h>
#include "sprintf.h"

unsigned gcvt(double v, char *buffer, int width, int prec, int flag) {
	double v_abs;
	int exponent;
	
	// inf / NaN
	if (isspecial(v, buffer)) {
		return strlen(buffer);
	}
	
	// absolute value
	if (v < 0.0) {
		v_abs = -v;
	} else {
		v_abs = v;
	}
	
	
	if (v_abs < DBL_MIN) {
		*buffer++ = '0';
		*buffer = 0;
		return 1;
	}
	
	// exponent
	exponent = 0;
	if (v_abs < 1.0) {
		while (v_abs < 1) {
		    v_abs *= 10.0;
		    exponent--;
		}
	} else {
		while (v_abs >= 10.0) {
			v_abs /= 10.0;
			exponent++;
		}
	}
	
	// select shortest format for exponent
	if (exponent > 7 || exponent < -7) {
		return ecvt(v, buffer, width, prec, flag);
	} else {
		return fcvt(v, buffer, width, prec, flag);
	}
}
